package com.dw.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.dw.dao.UserDao;
import com.dw.dao.jdbcUtils;
import com.dw.model.User;
import com.dw.util.DbConn;
import com.dw.dao.DAO;

/**
 *  数据库访问层-管理员的CRUD操作
 * @param <T>
 *
 */
public class UserDaoImpl<T> implements UserDao {
	private Connection conn = DbConn.getConn();
	//登陆用户验证
	  public boolean isLogin(User user){
		  boolean flag=false;
		  String sql="select * from t_manager where username=? and password=?";
		  try {
			PreparedStatement pmst=conn.prepareStatement(sql);
			pmst.setString(1, user.getUsername());//对传过来的用户名和密码进行封装
			pmst.setString(2, user.getPassword());
			ResultSet rs=pmst.executeQuery();
			if(rs.next()){
				flag=true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;	  
	  }

		 /**
		  * 修改用户的密码
		  * @param page
		  * @return
		  */
		
		public int updateUserPassWord(User  user) {
			int a=0;
			String sql = "update t_manager set password=? where username=?";
			try {
				PreparedStatement pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, user.getPassword());
				pstmt.setString(2, user.getUsername());
				a= pstmt.executeUpdate();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			return a;
		}
		public boolean addUser(User  user) {
			System.out.println("用户注册账号:"+user.getUsername());
			System.out.println("用户注册密码:"+user.getPassword());
			
			boolean flag = false;
			String sql = "insert into t_manager(username,password) values(?,?)";
			try {
				PreparedStatement psmt = conn.prepareStatement(sql);
				psmt.setString(1,user.getUsername());
				psmt.setString(2,user.getPassword());
				int i = psmt.executeUpdate();
				if (i == 1) {
					flag = true;
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return flag;
		}
		//返回name相等的记录数
		private QueryRunner  queryRunner=new QueryRunner();
		private Class<T> clazz;
	    public <E> E getForValue(String sql,Object ... args) {
	        Connection connection=null;
	       try{
	            connection=jdbcUtils.getConnection();
	            return (E) queryRunner.query(connection,sql,new ScalarHandler<T>(),args);
	        }catch(Exception e){
	            e.printStackTrace();
	        }finally{
	            jdbcUtils.releaseConnection(connection);
	        }
	        return null;
	    }
		public long getCountWithName(String name) {
			String sql = "SELECT count(ID) FROM t_manager WHERE USERNAME = ?";
			return getForValue(sql, name); 
		}

}
